<template>
  <view class="container">
    <!-- 显示加水印后的图片 -->
    <image v-if="watermarkedImage" :src="watermarkedImage" mode="widthFix" class="result-image" />

    <!-- 操作按钮区域 -->
    <view class="button-group">
      <button class="btn" @tap="chooseImage">选择图片</button>
      <button class="btn" @tap="saveResult" :disabled="!watermarkedImage">保存到相册</button>
      <button class="btn" @tap="uploadImage" :disabled="!watermarkedImage">上传图片</button>
    </view>

    <!-- 上传进度显示 -->
    <view v-if="uploadProgress > 0" class="progress-container">
      <progress :percent="uploadProgress" show-info stroke-width="3" />
      <text>{{ uploadStatus }}</text>
    </view>

    <!-- 隐藏的画布用于处理图片 -->
    <!-- <canvas canvas-id="watermarkCanvas" :style="{position: 'absolute', top: '-9999px', width: canvasWidth + 'px', height: canvasHeight + 'px'}"></canvas> -->
  </view>
</template>

<script>
  export default {
    data() {
      return {
        tempFilePath: '', // 原始图片路径
        watermarkedImage: '', // 加水印后的图片路径
        canvasWidth: 300, // 画布宽度
        canvasHeight: 400, // 画布高度
        uploadProgress: 0, // 上传进度
        uploadStatus: '', // 上传状态
        watermarkText: '13022223333' // 水印文字
      };
    },
    methods: {
      // 选择图片
      chooseImage() {
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            this.tempFilePath = res.tempFilePaths[0];
            this.addWatermark();
          },
          fail: (err) => {
            uni.showToast({
              title: '选择图片失败',
              icon: 'none'
            });
          }
        });
      },

      // 添加水印
      addWatermark() {
        uni.showLoading({
          title: '处理中...',
          mask: true
        });

        const that = this
        // 获取图片信息
        uni.getImageInfo({
          src: this.tempFilePath,
          success: (imageInfo) => {
            that.canvasWidth = imageInfo.width;
            that.canvasHeight = imageInfo.height;

            // 使用nextTick确保画布已渲染
            that.$nextTick(() => {
              // 创建离屏画布
              const canvas = uni.createOffscreenCanvas({
                type: '2d',
                width: that.canvasWidth,
                height: that.canvasHeight
              });
              const ctx = canvas.getContext('2d');

              // 绘制原始图片
              const img = canvas.createImage();
              img.onload = () => {
                ctx.drawImage(img, 0, 0, that.canvasWidth, that.canvasHeight);

                // 设置水印样式
                // ctx.setFontSize(40);
                // ctx.setFillStyle('rgba(255, 255, 255, 0.7)');
                // ctx.setTextAlign('center');
                // ctx.setTextBaseline('middle');
                ctx.font = "40px sans-serif"
                ctx.fillStyle = "#999"
                // ctx.textAlign = "center"

                // 计算水印位置（图片中心）
                // const x = that.canvasWidth / 2;
                // const y = that.canvasHeight / 2;
                const x = 20;
                const y = that.canvasHeight - 50;

                // 绘制水印文字
                ctx.fillText(that.watermarkText, x, y);

                // 绘制到画布
                  // 将画布内容导出为图片
                  uni.canvasToTempFilePath({
                    canvas,
                    fileType: 'jpg',
                    quality: 0.9,
                    success: (res) => {
                      that.watermarkedImage = res.tempFilePath;
                      uni.hideLoading();
                    },
                    fail: () => {
                      uni.hideLoading();
                      uni.showToast({
                        title: '生成水印失败',
                        icon: 'none'
                      });
                    }
                  });
              };
              img.src = that.tempFilePath;
              // ctx.drawImage(that.tempFilePath, 0, 0, that.canvasWidth, that.canvasHeight);

            });
          },
          fail: () => {
            uni.hideLoading();
            uni.showToast({
              title: '获取图片信息失败',
              icon: 'none'
            });
          }
        });
      },

      // 保存到相册
      saveResult() {
        uni.saveImageToPhotosAlbum({
          filePath: this.watermarkedImage,
          success: () => {
            uni.showToast({
              title: '保存成功'
            });
          },
          fail: () => {
            uni.showToast({
              title: '保存失败',
              icon: 'none'
            });
          }
        });
      },

      // 上传图片
      uploadImage() {
        this.uploadProgress = 0;
        this.uploadStatus = '上传中...';

        uni.uploadFile({
          url: '/api/upload',
          filePath: this.watermarkedImage,
          name: 'image',
          header: {
            'Authorization': 'Bearer your_token_here' // 替换为实际token
          },
          formData: {
            watermark: this.watermarkText
          },
          success: (res) => {
            if (res.statusCode === 200) {
              this.uploadStatus = '上传成功';
              uni.showToast({
                title: '上传成功'
              });
            } else {
              this.uploadStatus = `上传失败: ${res.data}`;
              uni.showToast({
                title: '上传失败',
                icon: 'none'
              });
            }
          },
          fail: () => {
            this.uploadStatus = '网络错误';
            uni.showToast({
              title: '网络错误',
              icon: 'none'
            });
          },
          complete: () => {
            setTimeout(() => {
              this.uploadProgress = 0;
              this.uploadStatus = '';
            }, 2000);
          }
        });
      }
    }
  };
</script>

<style>
  .container {
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .result-image {
    width: 90%;
    margin: 20rpx 0;
    border-radius: 10rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .button-group {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    margin-top: 30rpx;
    width: 100%;
  }

  .btn {
    margin: 10rpx;
    padding: 15rpx 30rpx;
    background-color: #007aff;
    color: white;
    border-radius: 10rpx;
    font-size: 28rpx;
  }

  .btn[disabled] {
    background-color: #cccccc;
    opacity: 0.6;
  }

  .progress-container {
    width: 80%;
    margin-top: 30rpx;
    text-align: center;
  }
</style>